
#include "typedef.h"
#include "macros.h"
#include "board.h"
#include "hal_int.h"
#include "hal_ext_int.h"
#include "hal_timer2.h"


static ISR_FUNC_PTR timer2_comp_isr = {0};

//----------------------------------------------------------------------------------
//  void  void hal_Timer2_Init(void)
//
//  DESCRIPTION:
//    Initialize the Timer2:
//      1.Using asynchronous mode, using CTC mode,clock rate CLK/256;
//      2.Enable interrupt of Timer2 compare Interrupt
//
//  ARGUMENTS:
//    None
//
//  RETURNS:
//    None
//----------------------------------------------------------------------------------
void halTimer2Init(void)
{
    INT32U  num;
    INT32U  denom;

    TCCR2  = 0x00;                                      /* Set TIMER0 prescaler to CTC Mode, CLK/256   */
    TCNT2  =    0;                                      /* Start TCNT at 0 for a new cycle             */
    ASSR  =  0x08; //set async mode
    num    = (INT32U)TIMER2_CLK;
    denom  = (INT32U)TICKS_PER_SEC;
    OCR2   = (INT8U)((2 * num / (8 * denom) + 1) / 2 - 1);
    TCCR2 = 0x0A;

    TIFR  |= BV(OCF2);                                      /* Clear  TIMER2 compare Interrupt Flag        */
    TIMSK |= BV(OCIE2);                                      /* Enable TIMER2 compare Interrupt             */
}

//----------------------------------------------------------------------------------
//  void _timer2_comp_ISR(void)
//
//  DESCRIPTION:
//    TIMER2 compare interrupt entry function
//
//  ARGUMENTS:
//    None
//
//  RETURNS:
//    None
//----------------------------------------------------------------------------------
#pragma vector=TIMER2_COMP_vect
__interrupt void _timer2_comp_ISR(void)
{
    if((TIMSK & (BV(OCIE2))) && (timer2_comp_isr != 0))
    {
       timer2_comp_isr();
    }
}

//----------------------------------------------------------------------------------
//  INT8U halTimer2CompIntConnect(ISR_FUNC_PTR func)
//
//  DESCRIPTION:
//    Connect TIMER2 compare interrupt with the user defined ISR function
//
//  ARGUMENTS:
//    func         - user defined ISR function
//
//  RETURNS:
//    TRUE  - the connect operation success
//    FALSE - the connect operation failed
//----------------------------------------------------------------------------------
INT8U halTimer2CompIntConnect(ISR_FUNC_PTR func)
{
   if(func)
   {
      timer2_comp_isr = func;
      return TRUE;
   }
   else
      return FALSE;
}
